<?php

namespace App\Http\Middleware;

use App\Models\User;
use App\Models\UserTokens;
use Closure;

/**
 * 前台token验证
 * Class Api
 * @package App\Http\Middleware
 */
class Api
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $authori = \Request::header('Authorization');
        $authori = explode(' ',$authori);
        $platform = \Request::header('platform');

        if(empty($platform)){
            return $this->login_error('登录平台不能为空');
        }
        if(empty($authori) || empty($authori[1])){
            return $this->login_error('错误token');
        }
        $access_token = $authori[1];
        $user = [];
        if ($access_token){
            $token = null;
            $query = UserTokens::where(['access_token'=>$access_token]);


            if($platform != 'wxapp'){           //小程序不需要判断token失效
                $platform = strtoupper($platform);
                $query->where(['platform' => $platform]);
                $token = $query->first();

                //token是否已经失效
                if(empty($token) || time() > $token->expires_time){
                    return $this->login_error('token已过期，请重新登录');
                }
            }else{
                $token = $query->first();

                if(empty($token)){
                    return $this->login_error('token平台错误，请重新登录');
                }
            }

            $uid = $token->uid;

            $user = User::find($uid);

            $request->userInfo = $user;
        }

        if (!$access_token || !$user){

            return $this->login_error('错误token');
        }
        return $next($request);
    }


    private function login_error($msg){
        return response()->json([
            'status' => 401,
            'data' => [
                'need_login'=>1
            ],
            'msg' => $msg
        ], 200, ['charset' => 'utf-8']);
    }
}
